package com.zf.shuashua.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.view.ViewCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.meis.base.mei.utils.NumberUtils;
import com.meis.base.mei.utils.SoftKeyboardUtils;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseActivity;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.FocusType;
import com.zf.shuashua.bean.ToggleLikeBean;
import com.zf.shuashua.bean.comment.CommentEntity;
import com.zf.shuashua.bean.home.HotVideoEntity;
import com.zf.shuashua.event.HotVideoEvent;
import com.zf.shuashua.event.RecordPlayEvent;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.dialog.BottomCommentDialog;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.widget.SampleCoverVideo;

import org.greenrobot.eventbus.EventBus;

public class HotVideoDetailActivity extends BaseActivity {

    public static final String DATA = "data";
    private static final String OPTION_VIEW = "view";

    private HotVideoEntity videoEntity;

    private SampleCoverVideo detailPlayer;

    private boolean isPlay = true;
    private boolean isPause;
    private OrientationUtils orientationUtils;
    private CommentListFragment commentListFragment;
    private ImageView ivAvatar;
    private TextView tvName;
    private TextView tvTitle;

    private LinearLayout layoutPraise;
    private ImageView ivPraise;
    private TextView tvPraiseNum;

    private ImageView ivHeader;
    private TextView tvFollow;
    private ImageView ivShare;

    private BottomCommentDialog mBottomCommentDialog;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            postUiThread(() -> SoftKeyboardUtils.hideSoftInput(mContext), 100);
        }
    };

    public static void startTActivity(Activity activity, HotVideoEntity entity, View transitionView) {
        Intent intent = new Intent(activity, HotVideoDetailActivity.class);
        // 这里指定了共享的视图元素
        intent.putExtra(DATA, entity);
        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionView, OPTION_VIEW);
        ActivityCompat.startActivity(activity, intent, options.toBundle());
    }

    @Override
    protected void initView() {
        try {
            Intent intent = getIntent();
            if (intent != null && intent.hasExtra(DATA)) {
                videoEntity = (HotVideoEntity) intent.getSerializableExtra(DATA);
            }
        } catch (Exception e) {
        }

        detailPlayer = findViewById(R.id.video_layout);
        ivAvatar = findViewById(R.id.iv_avatar);
        tvName = findViewById(R.id.tv_name);
        tvTitle = findViewById(R.id.tv_title);
        layoutPraise = findViewById(R.id.praise_layout);
        ivPraise = findViewById(R.id.iv_praise);
        tvPraiseNum = findViewById(R.id.tv_praise_num);
        ivHeader = findViewById(R.id.iv_header);
        tvFollow = findViewById(R.id.tv_follow);
        ivShare = findViewById(R.id.iv_share);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_hot_video_detail;
    }

    @Override
    protected void initData() {
        super.initData();
        detailPlayer.getTitleTextView().setVisibility(View.GONE);
        detailPlayer.getBackButton().setVisibility(View.GONE);
        detailPlayer.getBackButton().setOnClickListener(v -> onBackPressed());

        findViewById(R.id.back2).setVisibility(View.VISIBLE);
        findViewById(R.id.back2).setOnClickListener(v -> onBackPressed());

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        if (videoEntity != null) {
            GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();
            gsyVideoOption.setIsTouchWiget(true)
                    .setRotateViewAuto(false)
                    .setLockLand(false)
                    .setAutoFullWithSize(false)
                    .setShowFullAnimation(false)
                    .setNeedLockFull(true)
                    .setUrl(videoEntity.media_url)
                    .setCacheWithPlay(false)
                    .setVideoTitle(getNonText(videoEntity.description))
                    .setVideoAllCallBack(new GSYSampleCallBack() {
                        @Override
                        public void onPrepared(String url, Object... objects) {
                            super.onPrepared(url, objects);
                            //开始播放了才能旋转和全屏
                            orientationUtils.setEnable(true);
                            isPlay = true;
                            if(!Store.getInstance().isLogin()){
                                return;
                            }
                            HttpData.getInstance().reportHotWatch(videoEntity.id, 12, 15, new ACallback<BaseData>() {
                                @Override
                                public void onSuccess(BaseData data) {

                                }

                                @Override
                                public void onFail(int errCode, String errMsg) {
                                }
                            });
                        }

                        @Override
                        public void onQuitFullscreen(String url, Object... objects) {
                            super.onQuitFullscreen(url, objects);
                            if (orientationUtils != null) {
                                orientationUtils.backToProtVideo();
                            }
                        }
                    }).setLockClickListener((view, lock) -> {
                if (orientationUtils != null) {
                    //配合下方的onConfigurationChanged
                    orientationUtils.setEnable(!lock);
                }
            }).build(detailPlayer);

            detailPlayer.getFullscreenButton().setOnClickListener(v -> {
                //直接横屏
                orientationUtils.resolveByClick();
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(mContext, true, true);
            });

            detailPlayer.loadCoverImage(videoEntity.avatar, Color.parseColor("#000000"));

            // 开始播放
            if (videoEntity.currentPosition != 0) {
                detailPlayer.setSeekOnStart(videoEntity.currentPosition);
            }
            if (!videoEntity.is_video_paused) {
                detailPlayer.startPlayLogic();
            }

            // 这里指定了被共享的视图元素
            ViewCompat.setTransitionName(detailPlayer, OPTION_VIEW);

            if (findFragment(CommentListFragment.class) == null) {
                loadRootFragment(R.id.fl_container, commentListFragment = CommentListFragment.newInstance(videoEntity.id + ""));
            }

            Glide.with(mContext)
                    .load(videoEntity.user.avatar + "")
                    .circleCrop()
                    .into(ivAvatar);
            tvName.setText(getNonEmpty(videoEntity.user.name));
            tvTitle.setText(getNonEmpty(videoEntity.description));

            tvPraiseNum.setText(NumberUtils.INSTANCE.convertOneDecimalW(videoEntity.praise_count));
            ivPraise.setImageResource(videoEntity.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);
            layoutPraise.setOnClickListener(v -> {
                if (!Store.getInstance().isLogin()) {
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    v.setEnabled(false);
                    boolean isPraise = videoEntity.is_praise_user;
                    isPraise = !isPraise;
                    int praiseCount = videoEntity.praise_count;
                    if (isPraise) {
                        videoEntity.praise_count = praiseCount + 1;
                    } else {
                        videoEntity.praise_count = (praiseCount - 1) < 0 ? 0 : (praiseCount - 1);
                    }
                    videoEntity.is_praise_user = isPraise;

                    tvPraiseNum.setText(NumberUtils.INSTANCE.convertOneDecimalW(videoEntity.praise_count));
                    ivPraise.setImageResource(videoEntity.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);

                    final boolean isFinalPraise = isPraise;
                    reportAdvertAction(TrackConstants.ACTION_HOME_LIKE, TrackConstants.NOTE_HOME_LIKE);
                    HttpData.getInstance().toToggleLike(videoEntity.id, new AbsCallback<BaseData<ToggleLikeBean>>() {
                        @Override
                        public void onRealSuccess(BaseData<ToggleLikeBean> data2) {
                            if (data2 == null || data2.getData() == null) {
                                ToastUtil.showToast(mContext, "系统错误");
                                return;
                            }
                            v.setEnabled(true);
                            EventBus.getDefault().post(new HotVideoEvent(videoEntity.is_praise_user, videoEntity.praise_count));
                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            int praiseCount = videoEntity.praise_count;
                            if (!isFinalPraise) {
                                videoEntity.praise_count = praiseCount + 1;
                            } else {
                                videoEntity.praise_count = (praiseCount - 1) < 0 ? 0 : (praiseCount - 1);
                            }
                            videoEntity.is_praise_user = !isFinalPraise;

                            tvPraiseNum.setText(NumberUtils.INSTANCE.convertOneDecimalW(videoEntity.praise_count));
                            ivPraise.setImageResource(videoEntity.is_praise_user ? R.drawable.no_love_hot : R.drawable.love_hot);

                            v.setEnabled(true);
                        }
                    });
                }
            });

            if (videoEntity.user != null && !TextUtils.isEmpty(videoEntity.user.avatar)) {
                Glide.with(mContext)
                        .load(videoEntity.user.avatar)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(ivHeader);
            }

            findViewById(R.id.comment_layout).setOnClickListener(v -> {
                if (!Store.getInstance().isLogin()) {
                    jumpLogin();
                    return;
                }

                if (mBottomCommentDialog != null) {
                    mBottomCommentDialog.dismiss();
                    mBottomCommentDialog = null;
                }

                showDialog(mBottomCommentDialog = new BottomCommentDialog(videoEntity.id + "", "", 0, "", false, false, new BottomCommentDialog.OnPublishListener() {
                    @Override
                    public void onPublish(int position, boolean isAt, boolean isLevel2Reply, CommentEntity entity) {
                        if (isAt) return;
                        if (commentListFragment != null) {
                            commentListFragment.insertData(position, entity);
                        }

                        if (commentListFragment.isItemEmptyPage()) {
                            commentListFragment.setItemEmptyPage(false);
                            commentListFragment.removeItemEmpty();
                        }
                    }

                    @Override
                    public void onCloseKeyboard() {
                        mHandler.sendEmptyMessage(1);
                    }
                }));

            });

            tvFollow.setVisibility(videoEntity.follow_status == 0 ? View.VISIBLE : View.INVISIBLE);
            tvFollow.setOnClickListener(v -> {
                if (!Store.getInstance().isLogin()) {
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                }
                requestFollow(videoEntity.user_id);
            });


//            ivShare.setOnClickListener(v -> {
//                if (!Store.getInstance().isLogin()) {
//                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
//                } else {
//                    reportAdvertAction(TrackConstants.ACTION_HOME_SHARE, TrackConstants.NOTE_HOME_SHARE);
//                    Store.getInstance().setVideoId(String.valueOf(videoEntity.id));
//                    new XPopup.Builder(mContext)
//                            .hasShadowBg(false) // 去掉半透明背景
//                            .asCustom(new ShareVideoPopup(mContext, videoEntity.description, videoEntity.description, videoEntity.id + ""))
//                            .show();
//                }
//            });
        }

    }

    private String getNonText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    private void requestFollow(int userId) {
        HttpData.getInstance().getFocusType(userId, new AbsCallback<BaseData<FocusType>>() {
            @Override
            public void onRealSuccess(BaseData<FocusType> data) {
                switch (data.getData().getFollow_status()) {
                    //未关注
                    case 0:
                        break;
                    case 1://已关注
                    case 2://相互关注
                        tvFollow.setVisibility(View.INVISIBLE);
                        Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new HotVideoEvent(true));
                        break;
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                LogUtil.d(errMsg);
            }
        });
    }

    private void jumpLogin() {
        startActivity(new Intent(mContext, LoginActivity.class));
    }

    private void reportAdvertAction(String action, String note) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_HOME, action, note);
    }

    @Override
    public void onBackPressedSupport() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        // 发送记录播放状态事件
        if (detailPlayer != null) {
            EventBus.getDefault().post(new RecordPlayEvent(detailPlayer.getCurrentState() != GSYVideoView.CURRENT_STATE_PLAYING, detailPlayer.getCurrentPositionWhenPlaying()));
        }
        super.onBackPressedSupport();
    }

    @Override
    protected void onPause() {
        detailPlayer.getCurrentPlayer().onVideoPause();
        super.onPause();
        isPause = true;
        // 退出全屏
        GSYVideoManager.backFromWindowFull(this);
    }

    @Override
    protected void onResume() {
        // detailPlayer.getCurrentPlayer().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPlay) {
            detailPlayer.getCurrentPlayer().release();
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }


}
